<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Promise对象的其他方法</title>
</head>
<body>
  
</body>

<script type="text/javascript">
  
  let p = new Promise(resolve => {
    return resolve('foo')
  })
  p.then((data) => {
    console.log(data);
  })

  // 等价于 new Promise(resolve => {})
  let p1 = Promise.resolve('foo')
  p1.then(data => {
    console.log(data);
  })

  console.log('p', p);
  console.log('p1', p1);

  // Promise.all():异步并行，所有条件都完成，才做最终的事情
  let promise1 = new Promise((resolve, reject) => {})
  let promise2 = new Promise((resolve, reject) => {})
  let promise3 = new Promise((resolve, reject) => {})
  let promise4 = Promise.all([promise1, promise2, promise3])

  function all() {
    promise4.then(() => {
      console.log('success');
    
    }).catch(err => {
      console.log(err);
    })
  }
  all()

  // Promise.race()：给某个异步请求设置超时时间，并且在超时后执行相应的操作
  // 1、请求图片资源
  function imageRequset(imageSrc) {
    return new Promise((resolve, reject) => {
      const image = new Image()
      image.src = imageSrc
      image.onload = function() {
        resolve(image)
      }
    })
  }

  function timeout(ms) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('图片请求超时'))
      }, ms);
    }) 
  }

  let imageSrc = 'https://www.keaitupian.cn/cjpic/frombd/1/253/3942834720/1120395373.jpg'
  Promise.race([imageRequset(imageSrc), timeout(30000)])
  .then(data => {
    console.log(data);
    document.body.appendChild(data)
  }).catch(error => {
    console.log(error);
  }).finally(() => console.log('aaa'))
  

</script>
</html>